<?php

namespace app\index\controller;

use think\Controller;
use think\Request;
use think\Db;
use think\Exception;


class lesson extends IndexController
{
    /**
     * 课程视频播放页
     */
    public function classVideo ($id)
    {
        // dump($id);die;
        // 遍历笔记/课程
        $noteList = Db::name('notes')
            ->field('id, updatetime, unitename, content')
            ->where('cid',$id)
            ->where('uid', session('web')['uid'])
            ->order('updatetime', 'desc')
            ->select();

        $res = Db::name('courseunite')
            ->field('name, courseid')
            ->where('id', $id)
            ->find();
        $classname = $res['name'];
        $cid = $res['courseid'];


        return view('lesson/lessons', [
            'notes' => $noteList,
            'classid' => $id,
            'classname' => $classname,
            'cid' => $cid

        ]);
    }


    /**
     *  视频页通过ajax增加笔记
     */
    public function ajaxSave ()
    {
        // 获取数据
        $res = input('post.');
        $data['uniteid'] = $res['uniteid'];
        $data['unitename'] = $res['classname'];
        $data['cid'] = $res['cid'];
        $data['uid'] = session('web')['uid'];
        $data['mktime'] = time();
        $data['updatetime'] = time();
        $data['content'] = $res['content'];

        // 开启事件
        Db::startTrans();
        try{
            $num = Db::name('notes')
                ->insertGetId($data);
            if($num>0){
                Db::commit();
                return $num;
            }
        }catch(Exception $exception){
            Db::rollback();
            return "no";
        }
    }


    /**
     *  视频页通过ajax更新笔记
     * @return int
     */
    public function ajaxUpdate ()
    {
        // 获取数据
        $res = input('post.');
        $data['id'] = $res['id'];
        $data['content'] = $res['content'];
        $data['updatetime'] = time();

        // 开启事件
        Db::startTrans();
        try{
            $num = Db::name('notes')
                ->where('id', $data['id'])
                ->update($data);
            if($num>0){
                Db::commit();
                return 200;
            }
        }catch(Exception $exception){
            Db::rollback();
            return 404;
        }
    }


    /**
     * 删除笔记
     */
    public function ajaxDelete ()
    {
        // 获取nid
        $id = input('post.')['id'];

        // 开启事件
        Db::startTrans();
        try{
            $num = Db::name('notes')
                ->where('id', $id)
                ->delete();
            if($num>0){
                Db::commit();
                return 200;
            }
        }catch(Exception $exception){
            Db::rollback();
            return 404;
        }

    }
}
